package com.dk.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dk.pojo.user.TbUser;
import com.dk.service.integral.IntegralData;
import com.dk.service.integral.IntegralService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RocketMQMessageListener(topic = "integral",consumerGroup = "consumer-1905")
public class IntegralMQConsumer implements RocketMQListener<IntegralData>, RocketMQPushConsumerLifecycleListener {
    @Reference
    private IntegralService integralService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void onMessage(IntegralData integralData) {
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        Long userId = user.getId();
        int i = integralService.inserIntegral(integralData,userId);
    }

    /**
     * 自定义消息消费重试策略（手动接管ACK确认机制）
     * CONSUME_SUCCESS、RECONSUME_LATER
     * 注意：保留原有消费者监听RocketMQListener
     */
    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext context) {
                MessageExt messageExt = null;
                try {
                    messageExt = list.get(0);
                } catch (Exception e) {
                    e.printStackTrace();
                    int times = messageExt.getReconsumeTimes();
                    if (times == 2) {
                        redisTemplate.opsForValue().set(messageExt.getMsgId(),"消息错误");
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                    // 该条消息可以存储到DB或者LOG日志中，或其他处理方式，然后重试
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;// 重试
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
    }
}
